<?php 
/**
*file mysql.class.php
*
*数据库类
*@extends Db
*
*@param 放静态对象 $ins
*@param 连接数据库 $conn
*@param array $conf
*/
defined('ACC') ||exit ('ACC Denied');

class Mysql extends Db{
	private static $ins = null;
	private $conn = null;
	private $conf = array();
/**
*构造函数 保护防止new
*/
protected function __construct() {
    $this->conf = conf::getIns();
    
    $this->connect($this->conf->host,$this->conf->user,$this->conf->pwd);
    $this->select_db($this->conf->db);
    $this->setChar($this->conf->char);
}
/**
*析构函数
*/
public function __destruct(){
}

/**
*开放的静态方法
*/
public static function getIns(){
	if (!(self::$ins instanceof self)) {
		self::$ins = new self();
	   }
        return self::$ins;   
}

/**
*连接数据库服务器
*/
public function connect($h,$u,$p){
	$this->conn = mysql_connect($h,$u,$p);
	if (!$this->conn) {
		$err = new Exception('连接失败');
		throw $err;
	}
}

/**
*连接数据库
*@param 数据库名 $db
*/
protected function select_db($db){
	$sql = 'use '. $db;
	$this->query($sql);
}

/**
*设置编码
*@param 编码 $char 
*return bool
*/
protected function setChar($char){
	$sql = 'set names '. $char;
	return $this->query($sql);
}

/**
*设置执行sql语句
*@param sql语句 $sql
*@param resouce $rs
*
*Log::write 引用记录日志方法
*/
public function query($sql){
	$rs = mysql_query($sql,$this->conn);
	Log::write($sql);
	return $rs;
}

/**
*拼接执行insert/update语句
*@param 表名 $table
*@param array $arr
*@param string $mode
*@param string $where
*return resouce
*/
public function autoExecute($table,$arr,$mode='insert',$where=' where 1 limit 1'){
	if (!is_array($arr)) {
		return false;
	}

	if ($mode == 'update') {
		$sql = 'update ' . $table . ' set ';
		foreach ($arr as $k => $v) {
			$sql .= $k . "='" . $v ."',";
		    }
		    $sql = rtrim($sql,',');
		    $sql .= $where;
		    return $this->query($sql);
	}

	$sql = 'insert into '. $table . ' (' . implode(',', array_keys($arr)) . ')';
	$sql .= ' values (\'';
	$sql .= implode("','", array_values($arr));
	$sql .= '\')';
	return $this->query($sql);
}

/**
*查询所有数据
*@param select语句 $sql
*return array $list
*/
public function getAll($sql){
	$rs = $this->query($sql);
	$list = array();
	while ($row = mysql_fetch_assoc($rs)) {
		$list[] = $row;
	}
	return $list;
}

/**
*查询一行数据
*@param select语句 $sql
*@param resouce $rs
*return array $row
*/

public function getRow($sql){
	$rs = $this->query($sql);
    return mysql_fetch_assoc($rs);
}

/**
*查询一个数据
*@param select $sql
*@param resouce $rs
*return array[0]
*/
public function getOne($sql){
	$rs = $this->query($sql);
	$row = mysql_fetch_row($rs);
	return $row[0];	
}

/**
*返回影响的行数
*
*/
public function affected_row(){
	return mysql_affected_rows($this->conn);
}

/**
*返回最新auto_increment列的自增长的值
*/
public function insert_id(){
	return mysql_insert_id($this->conn);
}


}
?>